package com.lin.reggie.controller;

import com.lin.reggie.common.R;
import com.lin.reggie.entity.Employee;
import com.lin.reggie.entity.Page;
import com.lin.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/employee")
public class EmpolyeeController {

    @Autowired
    private EmployeeService employeeService;

    //登录
    @PostMapping("/login")
    public R<Employee>login(@RequestBody Employee employee, HttpSession session){
        //封装参数到对象，传递给service并且获取结果
        R<Employee> login = employeeService.login(employee);

        if (login.getCode()==1){
            session.setAttribute("employee",login.getData().getId());
        }
        //返回数据
        return login;
    }
    //退出按钮
    @PostMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "1";
    }

    //页面查询，分页查询
    @GetMapping("/page")
    public R<Page<Employee>>findByPage(Integer page,Integer pageSize,String name){
        Page<Employee> byPage = employeeService.findByPage(page, pageSize, name);
        return R.success(byPage);
    }

    //添加员工

    @PostMapping
    public R<String>save(@RequestBody Employee employee,HttpSession session){
        //获取登录数据中的存储id
        Long id = (Long) session.getAttribute("employee");
        //完善数据
        //创建人
        employee.setCreateUser(id);
        employee.setUpdateUser(id);
        employeeService.save(employee);
        return R.success("添加成功");
    }
    //按钮启用与禁用
    @PutMapping
        public R<String>status(@RequestBody Employee employee, HttpSession session){
            //获取当前会话域中操作人的id
            Long id = (Long) session.getAttribute("employee");
            //完善数据修改人
            employee.setUpdateUser(id);
            //调用业务层修改
            employeeService.status(employee);
            return R.success("修改成功");
    }
    @GetMapping("/{id}")
    public R<Employee>findById(@PathVariable Long id){
        R<Employee> byId = employeeService.findById(id);
        return byId;
    }
}
